﻿using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Microsoft.WindowsAPICodePack.Dialogs;
namespace ForguncyPluginCreator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();

        }

        MainWindowViewModel ViewModel
        {
            get
            {
                return this.DataContext as MainWindowViewModel;
            }
        }

        public class MainWindowViewModel : ModelBase
        {
            public MainWindowViewModel()
            {
                this.Name = "MyPlugin";
            }

            private string _name;
            public string Name
            {
                get
                {
                    return this._name;
                }
                set
                {
                    if (_name != value)
                    {
                        var oldValue = this._name;
                        this._name = value;
                        this.OnPropertyChanged();
                        if (string.IsNullOrEmpty(value))
                        {
                            return;
                        }
                        if (PluginPath == null)
                        {
                            this.PluginPath = GetDefaultFolder();
                        }
                        else
                        {
                            if(Path.GetFileName(PluginPath) == oldValue)
                            {
                                PluginPath = Path.Combine(Path.GetDirectoryName(PluginPath), value);
                            }
                        }
                    }
                }
            }

            public string LocaleName { get; set; } = "我的插件";

            public string GetDefaultFolder()
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "HZG-Plugins", "MyPlugin");
            }

            private string _forguncyInstallPath = @"C:\Program Files\Forguncy 8";
            public string ForguncyInstallPath
            {
                get
                {
                    return this._forguncyInstallPath;
                }
                set
                {
                    if (_forguncyInstallPath != value)
                    {
                        this._forguncyInstallPath = value;
                        this.OnPropertyChanged();
                    }
                }
            }

            private string _pluginPath;
            public string PluginPath
            {
                get
                {
                    return this._pluginPath;
                }
                set
                {
                    if (_pluginPath != value)
                    {
                        this._pluginPath = value;
                        this.OnPropertyChanged();
                    }
                }
            }

            private string _description = "这是一个活字格插件";
            public string Description
            {
                get
                {
                    return this._description;
                }
                set
                {
                    if (_description != value)
                    {
                        this._description = value;
                        this.OnPropertyChanged();
                    }
                }
            }
            public bool ContainCellType { get; set; } = true;
            public bool ContainCommand { get; set; } = true;
            public bool ContainServerCommand { get; set; } = true;
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.ViewModel.Name))
            {
                ShowError("插件名称不能为空");
                return;
            }
            if (!IsValidClassName( this.ViewModel.Name))
            {
                ShowError("请输入一个合法的插件名称，插件名称不能包含特殊字符，也不能是编程语言的关键字");
                return;
            }
            if (!this.ViewModel.ContainCellType && !this.ViewModel.ContainCommand && !this.ViewModel.ContainServerCommand)
            {
                ShowError("至少选择一种插件类型");
                return;
            }
            if (string.IsNullOrEmpty(this.ViewModel.ForguncyInstallPath))
            {
                ShowError("活字格设计器安装路径不能为空");
                return;
            }
            var forguncyExePath = Path.Combine(this.ViewModel.ForguncyInstallPath, "Website", "designerBin", "Forguncy.exe");
            if (!File.Exists(forguncyExePath))
            {
                ShowError("找不到文件：" + forguncyExePath);
                return;
            }
            if (Directory.Exists(ViewModel.PluginPath))
            {
                ShowError("文件夹：" + ViewModel.PluginPath + "已存在，请选择其他位置");
                return;
            }
            var templateFolder = Path.Combine("..", "ForguncyPluginTemplate");
            var targetFolder = ViewModel.PluginPath;


            var fileInfo = FileVersionInfo.GetVersionInfo(forguncyExePath);

            PluginProjectCreator.Create(templateFolder, targetFolder, this.ViewModel, fileInfo.FileVersion);
            MessageBox.Show("创建成功");
        }
        public static bool IsValidClassName(string identifier)
        {
            Microsoft.CSharp.CSharpCodeProvider csharpProvider = new Microsoft.CSharp.CSharpCodeProvider();
            return csharpProvider.IsValidIdentifier(identifier);
        }
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void ShowError(string message)
        {
            MessageBox.Show(message);
        }

        private void SelectInstallFolder_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new CommonOpenFileDialog();
            dlg.IsFolderPicker = true;
            dlg.InitialDirectory = ViewModel.ForguncyInstallPath;

            if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
            {
                this.ViewModel.ForguncyInstallPath = dlg.FileName;
            }
        }

        private void SelectPluginFolder_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new CommonOpenFileDialog();
            dlg.IsFolderPicker = true;
            var path = ViewModel.PluginPath ?? this.ViewModel.GetDefaultFolder();
            var lastFolderName = Path.GetFileName(path);
            dlg.InitialDirectory = Path.GetDirectoryName(path);

            if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
            {
                this.ViewModel.PluginPath = Path.Combine(dlg.FileName, lastFolderName);
            }
        }
    }
}
